/**
 * @file main.cpp
 *
 *  @date 10/12/2011
 *  @author Tales Miranda (tales.miranda84@gmail.com)
 *
 *  It's main file.
 */
#include <SDL.h>
#include <iostream>
#include "controller.hpp"
#include "view.hpp"
#include <exception>
#include <SDL_ttf.h>

#define SDL_CLIPBOARD_LIBRARY_STATIC
#include <SDL_Clipboard.h>

using namespace std;
using namespace yep;

SDL_Surface *screen = NULL;

namespace yep {

namespace frameCounter {

size_t currentFrame = 0;

}  // namespace frameCounter

}  // namespace yep

int main(int argc, char **argv)
{
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		cerr << SDL_GetError() << endl;
		return EXIT_FAILURE;
	}
	atexit(SDL_Quit);

	if (!(screen = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE | SDL_RESIZABLE)))
	{
		cerr << SDL_GetError() << endl;
		return EXIT_FAILURE;
	}

	if( TTF_Init() < 0)
	{
		cerr << TTF_GetError() << endl;
		return EXIT_FAILURE;
	}

	atexit(TTF_Quit);

	if(SDLScrap_Init() < 0)
	{
		cerr << SDL_GetError() << endl;
		return EXIT_FAILURE;
	}

	SDL_EnableUNICODE(1);

	SDL_WM_SetCaption("Yep Painter", NULL);

	try
	{
		Editor editor;
		Mode::setCurrentMode(DrawMode::getInstance());

		bool executing = true;
		while (executing)
		{
			SDL_Event event;
			SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 192, 192, 192));
			Mode &mode = Mode::getCurrentMode();

			while (SDL_PollEvent(&event))
			{
				switch (event.type)
				{
				case SDL_QUIT:
					executing = false;
					break;
				case SDL_VIDEORESIZE:
					if (!(screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_SWSURFACE | SDL_RESIZABLE)))
					{
						cerr << SDL_GetError() << endl;
						return EXIT_FAILURE;
					}
					break;
				default:
					mode.handle(editor, event);
					break;
				}
			}
			mode.logic(editor);
			mode.draw(editor, screen);
			SDL_Flip(screen);
			SDL_Delay(30);
			++frameCounter::currentFrame;
		}
	} catch (const Error &e)
	{
		cerr << e.explain() << endl;
		return EXIT_FAILURE;
	} catch (const exception & e)
	{
		cerr << e.what() << endl;
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

